<?php

/**
 * Created by PhpStorm.
 * User: yellow
 * Date: 2017/6/28
 * Time: 14:38
 */

namespace Admin\Service;

use Service\BaseService;

class QaService extends BaseService {



    public function __construct() {
        parent::__construct();
        $this->qaModel = M('question');
    }

    public function questionList($title,$cat_ids,$user_name,$mobile,$q_status,$a_status,$isPage = 1, $nowPage = 1) {

        if ($title) {
            $where['q.title'] = array('like', '%'.$title.'%');
        }

        if ($cat_ids) {
            foreach ($cat_ids as $cat_id){
                $temp[] = 'find_in_set('.$cat_id.',q.cat_ids)';
            }
            $where['_string'] = '('.implode(' or ',$temp).')';
        }

        if ($user_name) {
            $where['u.username'] = array('like', '%'.$user_name.'%');
        }

        if ($mobile) {
            $where['u.mobile'] = $mobile;
        }

        if (is_numeric($q_status) !== false) {
            $where['q.question_status'] = $q_status;
        }

        if (is_numeric($a_status) !== false) {
            $where['q.answer_status'] = $a_status;
        }

        $obj = $this->qaModel->alias('q')
            ->join('left join __USERS__ as u on q.user_id = u.user_id')
            ->join('left join __ANSWER__ as a on a.question_id = q.id')
            ->field('q.*,u.username,u.mobile,a.id as a_id,a.charge_view,a.charge_money')
             ->order('q.id desc');


        if ($where) {
            $obj->where($where);
        }
        if ($isPage) {
            $countRes = $obj->count();
            self::bPage($countRes);
            return self::resReturn(200, "success", self::$pageObj);
        } else {
            $lineList = $obj->page($nowPage, self::$pageNum)->select();
            return self::resReturn(200, 'success', $lineList);
        }
    }

    public function questionInfo($id) {
        $no_answer = array();
        $find = $this->qaModel->alias('q')
            ->join('left join __USERS__ as u on q.user_id = u.user_id')
            ->field('q.*,u.username,u.mobile')
            ->where('id  = '.(int)$id)->find();
        $has_answer = M('answer')->alias('a')
                ->join('left join __ACCOUNTANT_USERS__ as au on a.accountant_id = au.au_id')
                ->field('a.*,au.username,au.mobile')
                ->where('a.question_id = '.$id)->find();
        if(!$has_answer) {
            $no_answer = M('question_answer')->alias('qa')
                ->join('left join __ACCOUNTANT_USERS__ as au on qa.answer_id = au.au_id')
                ->field('qa.*,au.username,au.mobile')
                ->where('qa.question_id = ' . $id)->find();
        }
        return array(
            'info' => $find,
            'has_answer' => $has_answer,
            'no_answer' => $no_answer,
        );
    }


    public function handle($data = array()){

        $act = $data['act'];
        switch ($act){

            case 'add':

                unset($data['act']);
                $data['update_time'] = time();
                $res = $this->qaModel->add($data);

                break;
            case 'edit':

                unset($data['act']);
                $info = $data['info'];
                $info['cat_ids'] = implode(',', $info['cat_ids']);
                $info['stop_time'] = strtotime($info['stop_time']);
                $res = $this->qaModel->save($info);

                if($data['no_answer']){
                    $data['id'] = $data['no_answer']['id'];
                    $org = M('question_answer')->where('id = '.$data['id'].'')->getField('answer_id');
                    $res2 =  M('question_answer')->where('id = '.$data['id'].'')->data(array('answer_id' => $data['no_answer']['au_id']))->save();
                    if($res2 && $org != $data['no_answer']['au_id']){
                        $reg_id = M('accountant_users')->where("au_id = '".$data['no_answer']['au_id']."' ")->getField('registered_id');
                        if($reg_id) {
                            $this->jpush($info['id'], $reg_id, '您收到了一条问题，赶快去回复吧！');
                        }
                    }
                }
                if($data['has_answer']){
                    $data['has_answer']['add_time'] = strtotime($data['has_answer']['add_time']);
                    $res2 =  M('answer')->where('id = '.$data['has_answer']['id'].'')->data($data['has_answer'])->save();
                }

                $res = $res ? true : ( $res2 ? true : false);
                break;
            case 'del':
                $where['id'] = $data['id'];
                $res = $this->qaModel->where($where)->delete();
                 M('question_answer')->where('question_id = '.$where['id'].'')->delete();
                 M('answer')->where('question_id = '.$where['id'].'')->delete();
                break;
        }

        if ($res){
            return self::resReturn(200, 'success');
        } else{
            return self::resReturn(130, '操作失败');
        }

    }


    public function jpush($question_id,$reg_id,$txt,$type=1){
        $bool = false;
        Vendor("JPush.JPush");
        $client = new \JPush(xrkCache('jpush.jpush_appkey'),xrkCache('jpush.jpush_master_secret'));
        $result = $client->push()
            ->setPlatform('all')
            ->addRegistrationId($reg_id)
            ->addIosNotification($txt,'default', '+1', true, '',array('id' => $question_id))
            ->send();

        $result = $client->push()
            ->setPlatform('all')
            ->addRegistrationId($reg_id)
            ->addAndroidNotification($txt, '会计问答', 1, array('id' => $question_id))
            ->addIosNotification($txt,'default', '+1', true, '',array('id' => $question_id))
            ->sends();
        if($result->data->sendno){
            M('jpush_log')->save(array(
                'reg_id' =>$reg_id,
                'content' =>$txt,
                'question_id' =>$question_id,
                'type' =>$type,
                'status' =>1,
                'add_time' =>time(),
            ));
            $bool = true;
        }else{
            M('jpush_log')->save(array(
                'reg_id' =>$reg_id,
                'content' =>$txt,
                'question_id' =>$question_id,
                'type' =>$type,
                'status' =>0,
                'add_time' =>time(),
            ));
            $bool = false;
        }
        return $bool;
    }



}
